/*
 * @Author: xiaxia
 * @Description: 
 * @Date: 2023-06-08 17:35:19
 * @LastEditTime: 2023-12-20 11:22:40
 * @FilePath: \pdf-print\src\utils\printjs.js
 */
import axios from 'axios'
import {getLodop} from './LodopFuncs'
const instance = axios.create({
  timeout: 1000
})
var LODOP = getLodop(); // 创建一个LODOP对象

// 获取本地打印机 
function getLocalPrint() {
  let counter = LODOP.GET_PRINTER_COUNT(); // 获取打印机个数
  let printerList= []
  for (let i = 0; i < counter; i++) {
    printerList.push({//将打印机存入printerList数组中
      value: LODOP.GET_PRINTER_NAME(i),
      label: LODOP.GET_PRINTER_NAME(i)
    });
  }
  return printerList
}

// 打印Base64图片
const lodopImageBase64 = (img64, printer) => {
  if (!LODOP) return
  LODOP.PRINT_INIT("测试打印");
  // LODOP.SET_PRINT_PAGESIZE(2, 0, 0, 'A4') // 设置纸张大小
  LODOP.ADD_PRINT_IMAGE(0, 0, "100%", "100%", img64)
  LODOP.SET_PRINTER_INDEX(printer)
  LODOP.PREVIEW() // 预览
}

// 1. 模拟请求
const getFileBase64 = async pdfUrl => {
  let fileData = null
  try {
    fileData = await instance({
      method: 'get',
      url: pdfUrl, // 请求地址
      responseType: 'blob' // 指明服务器返回的数据类型
    })
  } catch {
    fileData = null
  }
  if (fileData && fileData.data) {
    const result = getObjectURL(fileData.data) // 流转成url
    return result
  } else {
    return false
  }
}
// 2.流转成url
const getObjectURL = (file) => {
  let url = null
  if (window.createObjectURL !== undefined) { // basic
    url = window.createObjectURL(file)
  } else if (window.webkitURL !== undefined) { // webkit or chrome
      try {
        url = window.webkitURL.createObjectURL(file)
      } catch (error) {
        console.log(error)
      }
  } else if (window.URL !== undefined) { // mozilla(firefox)
      try {
        url = window.URL.createObjectURL(file)
      } catch (error) {
        console.log(error)
      }
  }
    return url
  }

export  { getLocalPrint, lodopImageBase64, getFileBase64, getObjectURL }